import { Routers, routes as constantRouterMap } from '@/router'
import { ActionContext } from 'vuex'
import { State, RootState } from '@vue/runtime-core'
import { RouteRecordRaw, RouteMeta, _RouteRecordBase, RouteComponent } from 'vue-router'
import Layout from '@/layout/index.vue'
import ParentView from '@/components/ParentView/index.vue'
import { transformRouteToMenu } from '@/router/helper/menuhelper'


const permission = {
  state: () => ({
    // 当前真实的路由
    routers: constantRouterMap,
    // Backstage menu list
    backMenuList: [],
    // menu List
    addRouters: [],
    // 菜单映射的所有完整路由
    frontMenuList: []
  }),
  getters: {
    getBackMenuList(state: State): Routers[] {
      return state.backMenuList;
    },
    getFrontMenuList(state: State): Routers[] {
      return state.frontMenuList;
    },
    getRouters(state: State): Routers[] {
      return state.routers;
    }
  },
  mutations: {
    SET_ROUTERS: (state: State, routers: Array<RouteRecordRaw>) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    SET_FRONT_MENU_LIST: (state: State, routers: Array<RouteRecordRaw>) => {
      const frontMenuList = constantRouterMap.concat(routers)
      state.frontMenuList = transformRouteToMenu(frontMenuList, true);
    }
  },
  actions: {
    generateRoutes({ commit }: ActionContext<State, RootState>, asyncRouter: string[]) {

      commit('SET_ROUTERS', asyncRouter)
    },
    setFrontMenuList({ commit }: ActionContext<State, RootState>, sidebarRouter: string[]) {
      commit('SET_FRONT_MENU_LIST', sidebarRouter)
    },
  }
}



// 遍历后台传来的路由字符串，转换为组件对象
export const asyncRouter = (routers: Array<Routers>, router?: Routers, isRewrite = false) => {
  console.log(routers)
  const sidebarRoutes: Array<RouteRecordRaw> = []
  routers.forEach((router) => {
    const sidebarRoute: RouteRecordRaw = {
      component: Layout,
      path: router.path,
      name: router.name,
      meta: router.meta,
      redirect: router.redirect,
      children: []
    }
    if (isRewrite && router.children) {
      // 路由
      sidebarRoute.children = asyncRouterChildren(router.children)
    }

    if (router.component) {
      if (router.component === 'Layout') {  // 布局 
        sidebarRoute.component = Layout
      } else if (router.component === 'ParentView') {  // 路由出口
        sidebarRoute.component = ParentView
      } else {
        const component = router.component
        sidebarRoute.component = modules[`/src/views/${component}.vue`] as any
      }
    }
    if (router.children && router.children.length) {
      sidebarRoute.children = asyncRouter(router.children, router, isRewrite)
    }

    sidebarRoutes.push(sidebarRoute)
  })

  return sidebarRoutes
}

function asyncRouterChildren(childrenMap: Array<Routers>, routers?: Routers) {
  let children: Array<RouteRecordRaw> = []

  childrenMap.forEach((el) => {
    const sidebarRoute: RouteRecordRaw = {
      path: el.path,
      redirect: el.redirect,
      name: el.name,
      meta: el.meta,
      component: modules[`/src/views/${el.component}.vue`] as any
    }

    if (el.children && el.children.length) {
      if (el.component === 'ParentView') {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          const childRoute: RouteRecordRaw = {
            path: c.path,
            redirect: c.redirect,
            name: c.name,
            meta: c.meta,
            component: modules[`/src/views/${c.component}.vue`] as any
          }

          if (c.children && c.children.length) {
            children = children.concat(asyncRouterChildren(c.children, c))
            return
          }
          children.push(childRoute)
        })
        return
      }
    }
    children = children.concat(sidebarRoute)
  })
  return children
}

//引入所有views下.vue文件
const modules = import.meta.glob("/src/views/**/**.vue");

// export const loadView = (view: any) => {
//   return () => require.ensure([], (require) => require(`@/views/${view}`))

// vue2写法
// return (resolve: any) => require([`@/views/${view}`], resolve)

// }



export default permission